package com.eliza.ascl.conpv.provider

import android.content.ContentProvider
import android.content.ContentValues
import android.content.UriMatcher
import android.database.Cursor
import android.database.sqlite.SQLiteDatabase
import android.net.Uri


/*-*- coding:utf-8 -*-
 * @Author  : debi
 * @Time    : 5/9/22
 * @Software: Android Studio
 */
class UserProvider : ContentProvider() {
    companion object {
        private val USER_DIR = 0
        private val USER_ITEM = 1
        private val TABEL_NAME = "UserProvider.db"
        private val Db_NAME = "UserProvider"
        private val MATH_CODE = 1
        private val ADD_URI = "cn.wjx.contentprovider"
        private val PATH = "user"

        //content://cn.edu.cdut.provider/user/1
        var uriMatcher: UriMatcher? = null
    }


    lateinit var dbHelper: UserDatabaseHelper
    lateinit var db: SQLiteDatabase

    override fun onCreate(): Boolean {
        dbHelper = UserDatabaseHelper(context!!, TABEL_NAME, null, 1)
        db = dbHelper.writableDatabase
        return true
    }

    init {
        uriMatcher = UriMatcher(UriMatcher.NO_MATCH);
        /**
         * addURI(String authority, String path, int code);
         * content://
         *      authority：添加匹配规则，不同应用的唯一标识符,一般用包名+ .provider
         *      path：一般标识表名 包名+ .provider/userTable
         * code：dangURI被匹配之后会返回后面的matchCode
         */
        uriMatcher!!.addURI(ADD_URI, PATH, MATH_CODE);

    }

    override fun query(
        uri: Uri,//某一应用下的某张表
        projection: Array<out String>?,//查询的列名
        selection: String?,//where 约束条件
        selectionArgs: Array<out String>?,//where 约束条件占位符
        sortOrder: String?//查询出来排序方式
    ): Cursor? {
        var cursor: Cursor? = null
        when (UserProvider.uriMatcher!!.match(uri)) {
            UserProvider.USER_DIR -> cursor =
                db.query(TABEL_NAME, projection, selection, selectionArgs, null, null, null)
            UserProvider.USER_ITEM -> {
                val queryId = uri.pathSegments[1]
                cursor =
                    db.query(TABEL_NAME, projection, "_id = ?", arrayOf(queryId), null, null, null)
            }
        }

        return cursor
    }

    override fun getType(uri: Uri): String? {
        TODO("Not yet implemented")
    }

    override fun insert(uri: Uri, values: ContentValues?): Uri? {
        TODO("Not yet implemented")
    }

    override fun delete(uri: Uri, selection: String?, selectionArgs: Array<out String>?): Int {
        TODO("Not yet implemented")
    }

    override fun update(
        uri: Uri,
        values: ContentValues?,
        selection: String?,
        selectionArgs: Array<out String>?
    ): Int {
        TODO("Not yet implemented")
    }
}